package org.lhl.readruler.utils

import android.content.Context
import lhl.kotlinextends.e
import org.lhl.readruler.mApp
import java.lang.reflect.Type
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * Created by luohaolun.
 * Date: 2019/5/21
 */
private val sp by lazy { mApp.getSharedPreferences("app", Context.MODE_PRIVATE) }

class SharePreferencesDelegate<T>(private val def: T, private val type: Type) : ReadWriteProperty<Any, T> {

    override fun getValue(thisRef: Any, property: KProperty<*>): T {
        "读取${property.name}  ".e()
//        if (property.name == "userData"){
//            Exception("userdata").e()
//        }
        return when (type) {
            String::class.java -> sp.getString(property.name, def as String)
            Boolean::class.java -> sp.getBoolean(property.name, def as Boolean)
            Float::class.java -> sp.getFloat(property.name, def as Float)
            Int::class.java -> sp.getInt(property.name, def as Int)
            Long::class.java -> sp.getLong(property.name, def as Long)
            else -> {
                gson.fromJson(sp.getString(property.name, def?.toJson()), type)
            }
        } as T
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
        "保存${property.name}  ".e()
        val edit = sp.edit()
        when (type) {
            String::class.java -> edit.putString(property.name, value as String?)
            Boolean::class.java -> edit.putBoolean(property.name, value as Boolean)
            Float::class.java -> edit.putFloat(property.name, value as Float)
            Int::class.java -> edit.putInt(property.name, value as Int)
            Long::class.java -> edit.putLong(property.name, value as Long)
            else -> {
                edit.putString(property.name, value?.toJson())
            }
        }
        edit.commit()
    }
}